package com.github.data_manage.util

import com.github.data_manage.util.CollectionExtensions.splitBySize

/**
 *@author CHN
 *@since 2025-02-12 20:50
 */
object CollectionExtensions {

    fun <T> Collection<T>.containsAny(collection: Collection<T>): Boolean {
        for (t in collection) {
            if (this.contains(t)) {
                return true
            }
        }
        return false
    }

    fun <T> Collection<T>.splitBySize(splitSize: Int): List<List<T>> {
        var currentSize = 0
        val result = mutableListOf<List<T>>()
        var currentResult = mutableListOf<T>()
        for (t in this) {
            currentResult.add(t)
            currentSize += 1
            if (currentSize == splitSize) {
                result.add(currentResult)
                currentSize = 0
                currentResult = mutableListOf()
            }
        }
        if (currentResult.isNotEmpty()) {
            result.add(currentResult)
        }
        return result
    }

    inline fun <reified T> List<T>.toArray(): Array<T> =
        Array<T>(this.size) { i -> this[i] }

    fun <T> List<T>.getNullWhenOutOfIndex(index: Int): T? {
        if (index !in 0..<size) {
            return null
        }
        return get(index)
    }
}
